package cn.mdmm.controller.system;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.mdmm.common.MessageConstant;
import cn.mdmm.common.SpringSecurityUtils;
import cn.mdmm.controller.BaseController;
import cn.mdmm.entity.response.ResponseBodyToOne;
import cn.mdmm.entity.system.SysRole;
import cn.mdmm.entity.system.SysUser;
import cn.mdmm.service.system.SysDictService;
import cn.mdmm.service.system.SysUserService;
import cn.mdmm.shiro.DatabaseRealm;
import cn.modoumama.common.annotation.OpLog;
import cn.modoumama.common.exception.ServiceException;
import cn.modoumama.common.exception.SystemException;
import cn.modoumama.common.utils.ConfigProperty;
import cn.modoumama.common.utils.JSONUtils;
import cn.modoumama.page.GridDataModel;
import cn.modoumama.page.Page;

@Controller
@RequestMapping(value = "/system/prg/user")
@OpLog(logDesc = "系统操作员管理")
public class SysUserController extends BaseController {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysDictService sysDictService;
	@Autowired
	DatabaseRealm databaseRealm;

    @RequestMapping(value = "init")
    public String init(HttpServletRequest request) {
        Map<String, String> statusMap = sysDictService.getDetailValueMap("状态");
        request.setAttribute("statusMap", JSONUtils.toJson(statusMap));
        request.setAttribute("statusCombo", JSONUtils.toCombo(statusMap));
        Map<String, String> sexMap = sysDictService.getDetailValueMap("性别");
        request.setAttribute("sexMap", JSONUtils.toJson(sexMap));
        request.setAttribute("sexCombo", JSONUtils.toCombo(sexMap));
        SysUser sysUser = SpringSecurityUtils.getCurrentUser();
        Map<String, String> typeMap = sysDictService.getDetailValueMap("用户类型", sysUser.getUserType());
        request.setAttribute("typeMap", JSONUtils.toJson(typeMap));
        request.setAttribute("typeCombo", JSONUtils.toCombo(typeMap));
        return "system/user/init";
    }

    @RequestMapping(value = "list")
    @ResponseBody
    public GridDataModel list(HttpServletRequest request, SysUser user) {
    	logger.debug("method: list() ");
        Page po = getPage(request, null);
        po.addCondition("userNameLike", user.getUserName());
        po.addCondition("realName", user.getRealName());
        po.addCondition("userStatus", user.getUserStatus());
        po.addCondition("userType", user.getUserType());
        po.addCondition("gtUserType", SpringSecurityUtils.getCurrentUserType());
        po.addCondition("createTimeStart", request.getParameter("createTimeStart"));
        po.addCondition("createTimeEnd", request.getParameter("createTimeEnd"));
        po.addCondition("updateTimeStart", request.getParameter("updateTimeStart"));
        po.addCondition("updateTimeEnd", request.getParameter("updateTimeEnd"));
        GridDataModel gridDataModel = sysUserService.findGridDataModelByCondition(po);
		return gridDataModel;
    }

    @RequestMapping(value = "showAdd")
    public String showAdd(HttpServletRequest request) {
        Map<String, String> statusMap = sysDictService.getDetailValueMap("状态");
        request.setAttribute("statusMap", JSONUtils.toJson(statusMap));
        request.setAttribute("statusCombo", JSONUtils.toCombo(statusMap));
        Map<String, String> sexMap = sysDictService.getDetailValueMap("性别");
        request.setAttribute("sexCombo", JSONUtils.toCombo(sexMap));
        SysUser sysUser = SpringSecurityUtils.getCurrentUser();
        Map<String, String> typeMap = sysDictService.getDetailValueMap("用户类型", sysUser.getUserType());
        request.setAttribute("typeMap", JSONUtils.toJson(typeMap));
        request.setAttribute("typeCombo", JSONUtils.toCombo(typeMap));
        return "system/user/add";
    }

    @RequestMapping(value = "insert")
    public String insert(HttpServletRequest request, SysUser user) {
    	SysUser sysUser = SpringSecurityUtils.getCurrentUser();
    	//只能创建比自己大的级别（0为最高权限）
    	Integer userType = sysUser.getUserType();
    	if(user.getUserType()==null || userType == null  || user.getUserType()<=userType){
        	user.setUserType(userType+1);
    	}
    	sysUserService.insert(user);
        return "success";
    }

    @RequestMapping(value = "showEdit")
    public String showEdit(HttpServletRequest request,Long id) {
        SysUser sUser = sysUserService.findById(id);
        request.setAttribute("sUser", sUser);
        Map<String, String> statusMap = sysDictService.getDetailValueMap("状态");
        request.setAttribute("statusMap", JSONUtils.toJson(statusMap));
        request.setAttribute("statusCombo", JSONUtils.toCombo(statusMap));
        Map<String, String> sexMap = sysDictService.getDetailValueMap("性别");
        request.setAttribute("sexCombo", JSONUtils.toCombo(sexMap));
        SysUser sysUser = SpringSecurityUtils.getCurrentUser();
        Map<String, String> typeMap = sysDictService.getDetailValueMap("用户类型", sysUser.getUserType());
        request.setAttribute("typeMap", JSONUtils.toJson(typeMap));
        request.setAttribute("typeCombo", JSONUtils.toCombo(typeMap));
        return "system/user/edit";
    }

    @RequestMapping(value = "update")
    public String update(HttpServletRequest request, SysUser user) {
    	SysUser admin = SpringSecurityUtils.getCurrentUser();
        SysUser sysUser = sysUserService.findById(user.getId());
        sysUser.setEmail(user.getEmail());
        sysUser.setPhone(user.getPhone());
        sysUser.setRealName(user.getRealName());
        sysUser.setUserName(user.getUserName());
      //只能创建比自己大的级别（0为最高权限）
    	if(user.getUserType()!=null){
    		//是管理员才可以修改类别
    		if(admin.getUserType()<3  && user.getUserType()<=admin.getUserType()){
        		sysUser.setUserType(admin.getUserType()+1);
        	}else{
        		sysUser.setUserType(user.getUserType());
        	}
    	} 
        sysUser.setSex(user.getSex());
        sysUser.setUserStatus(user.getUserStatus());//状态变更
        sysUserService.updateById(sysUser);
        return "success";
    }

    @RequestMapping(value = "delete")
    @ResponseBody
    public ResponseBodyToOne delete(HttpServletRequest request, Long[] ids) {
		ResponseBodyToOne responseBody = new ResponseBodyToOne();
		logger.debug("method: delete() ");
        try {
            sysUserService.removeByIds(ids);
        } catch (Exception e) {
        	throw new ServiceException(MessageConstant.SYSTEM_ERROR);
        }
        return responseBody;
    }

    @RequestMapping(value = "initPwd")
    @ResponseBody
    public ResponseBodyToOne initPwd(HttpServletRequest request, PrintWriter out) {
		ResponseBodyToOne responseBody = new ResponseBodyToOne();
		logger.debug("method: initPwd() ");
        try {
            String ids = request.getParameter("ids");
            String[] aId = ids.split(",");
            for (String id : aId) {
            	String newPwd = ConfigProperty.getProperty("default.password");
                sysUserService.updateUserPwd(Long.valueOf(id),null,newPwd,newPwd);
            }
        } catch (Exception e) {
        	throw new ServiceException(MessageConstant.SYSTEM_ERROR);
        }
        return responseBody;
    }
    
    @RequestMapping(value = "roleList")
	public String menuTree(HttpServletRequest request, Long id){
    	//获取用户的角色
		request.setAttribute("userId", id);
		//获取所有的角色
		List<SysRole> roles = sysUserService.getAllRole(id);
		
		request.setAttribute("roles", roles);
		return "system/user/roleUser";
	}

    @RequestMapping(value = "bindingRole")
	public String bindMenu(HttpServletRequest request,Long userId,Long[] roleIds){
    	sysUserService.bindRoleUser(userId,roleIds);
    	SysUser user = sysUserService.findById(userId);
    	databaseRealm.clearCachedAuthorizationInfo(user.getUserName());
		return "success";
	}
    @RequestMapping(value = "checkUser")
    @ResponseBody
    public ResponseBodyToOne checkUserName(HttpServletRequest request, SysUser user) {
    	ResponseBodyToOne responseBody = new ResponseBodyToOne();
        Map<String, Object> condititon = new HashMap<String, Object>();
        condititon.put("userName", user.getUserName());
        condititon.put("phone", user.getPhone());
        List<SysUser> users = sysUserService.findModelsByCondition(condititon);
        if(users!=null && users.size() > 0 ){
        	if(user.getId() == null){
            	throw new SystemException("用户已存在");
        	}else if(!users.get(0).getId().equals(user.getId()) ){
        		throw new SystemException("用户已存在");
        	}
        }
        return responseBody;
    }

}
